import { Dept, User } from '@/types';
import { IAction, IModalProps } from '@/types/modal';
import { Modal, Form, Input, Select, TreeSelect } from 'antd';
import { useEffect, useImperativeHandle, useState } from 'react';
import { useForm } from 'antd/es/form/Form';
import { getDeptList, getAllUserList, createDept, editDept } from '@/api';
import { message } from '@/utils/AntdGlobal';

export default function CreateDept(props: IModalProps<Dept.EditorParams>) {
  const [action, setAction] = useState<IAction>('create');
  const [deptList, setDeptList] = useState<Dept.DeptItem[]>([]);
  const [visiable, setVisiable] = useState(false);
  const [userList, setUserList] = useState<User.UserItem[]>();
  const [form] = useForm();

  useEffect(() => {
    getDeptData();
    getAllUserData();
  }, []);
  useImperativeHandle(props.mRef, () => ({
    open
  }));

  const handleSubmit = async () => {
    const valid = await form.validateFields();
    if (valid) {
      if (action === 'create') {
        await createDept(form.getFieldsValue());
        message.success('创建成功');
      } else {
        await editDept(form.getFieldsValue());
        message.success('编辑成功');
      }
      setVisiable(false);
      props.update();
    }
  };
  const handleCancel = () => {
    setVisiable(false);
    form.resetFields();
  };
  const getDeptData = async () => {
    const data = await getDeptList();
    setDeptList(data);
  };
  const getAllUserData = async () => {
    const data = await getAllUserList();
    setUserList(data);
  };
  const open = (
    type: IAction,
    data?: Dept.EditorParams | { parentId: string }
  ) => {
    setAction(type);
    setVisiable(true);
    if (type === 'edit' && data) {
      form.setFieldsValue(data);
    }
    if (type === 'create' && data) {
      form.setFieldsValue({ parentId: data.parentId });
    }
  };
  return (
    <Modal
      title={action === 'create' ? '新增部门' : '编辑部门'}
      width={800}
      open={visiable}
      okText='确定'
      cancelText='取消'
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form form={form} labelAlign='right' labelCol={{ span: 4 }}>
        <Form.Item label='用户ID' name='_id' style={{ display: 'none' }}>
          <Input placeholder='请输入用户ID'></Input>
        </Form.Item>
        <Form.Item label='上级部门' name='parentId'>
          <TreeSelect
            placeholder='请选择上级部门'
            allowClear
            treeDefaultExpandAll
            fieldNames={{
              label: 'deptName',
              value: '_id'
            }}
            treeData={deptList}
          ></TreeSelect>
        </Form.Item>
        <Form.Item
          label='部门名称'
          name='deptName'
          rules={[{ required: true, message: '请输入部门名称' }]}
        >
          <Input placeholder='请输入部门名称'></Input>
        </Form.Item>
        <Form.Item
          label='负责人'
          name='userName'
          rules={[{ required: true, message: '请选择负责人' }]}
        >
          <Select placeholder='请选择部门负责人'>
            {userList?.map(user => {
              return (
                <Select.Option value={user.userName} key={user.userId}>
                  {user.userName}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
}
